﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PIBV;
using System.Collections;
using System.Net;
using System.Text.RegularExpressions;
using MTViewer;
using System.Configuration;
using System.Diagnostics;
using PP = MTViewer.Properties;

namespace PIMDownloader
{
    public partial class MainForm : Form
    {
        PID_Database db;
        string _pdfStoragePath = MTViewer.Properties.Settings.Default.PdfStoragePath;

        private static DbManager dbManager = new DbManager(MTViewer.Properties.Settings.Default.ConnectionString);

        bool bOnlyDownload = false;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //run the timer to begin download drawings
            //timer.Tick += new EventHandler((s, a) => {  timer.Enabled = false; InitDownload();});
            //timer.Enabled = true;
        }

        void RunDownload()
        {
            dbManager.Connect();

            db = dbManager.CreateObject<PID_Database>();
            db.FillData();

            IEnumerator enumerator = (db as IEnumerator);
            //begin to download drawings
            if (enumerator.MoveNext())
            {
                webBrowser.Navigate(String.Format("http://ti-sf.statoil.com/pimviewer36/PIMResultListDocument.aspx?ClassName=DocRevision&Name=*{0}*&Description=", enumerator.Current as string));
            }
        }

        void InitDownload()
        { 
            //Initialize PIM connection
            webBrowser.ScriptErrorsSuppressed = true;
            webBrowser.Navigate(@"http://lci.statoil.no/interface.asp?method=GetTag&Plant=SNO&TagNumber=123456789qwertyuiop");

            System.Threading.Thread.Sleep(10000);

            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            RunDownload();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //process downloaded document and download pdf and dwg files from
            WebClient cl = new WebClient();

            string dgnFileName = "";
            string pdfFileName = "";

            string doc = webBrowser.DocumentText;

            string str = "session has timed out";
            
            if (doc.Contains(str))
            {
                System.Threading.Thread.Sleep(500);
                Debug.WriteLine(" !!! session time out ");
                webBrowser.Navigate(@"http://lci.statoil.no/interface.asp?method=GetTag&Plant=SNO&TagNumber=123456789qwertyuiop");
            }

            //webBrowser.Stop();
            doc = doc.Substring(doc.IndexOf("<body"));
            
            //using regular expression try to find entrancies of links to downloaded files
            string pattern = @"((fu)\=\'\w+[^\']*)+";
            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            Match match = regex.Match(doc);
            
            while (match.Success)
            {
                string tagName = match.ToString().Replace("fu='", "");

                if (tagName.ToLower().EndsWith(".pdf"))
                {
                    pdfFileName = tagName;
                }
                else
                {
                    if (tagName.ToLower().EndsWith(".dgn") || tagName.ToLower().EndsWith(".dwg"))
                    {
                        dgnFileName = tagName;
                    }
                }

                match = match.NextMatch();
            }

            //try to download pdf file
            //try
            {
                Debug.WriteLine("       try to download file = " + pdfFileName);
                string tagName = pdfFileName;
                //string domain = tagName.Substring(1, tagName.LastIndexOf(@"/"));
                string fn = tagName.Remove(0, tagName.LastIndexOf(@"/") + 1);
                //download the file
                if (!System.IO.File.Exists(_pdfStoragePath + fn))
                {
                    try
                    {
                        cl.DownloadFile(tagName, _pdfStoragePath + fn);
                        Debug.WriteLine(" + file downloaded: " + fn);
                    }
                    catch
                    {
                        Debug.WriteLine(" Err. PIM Exception: fileName = " + fn);
                    }
                }
                else
                {
                    Debug.WriteLine(" ! file exists " + fn);
                }
            }
            //catch
            //{ }

            //try to download dgn file
            //try
            {
                Debug.WriteLine("       try to download file = " + dgnFileName);
                string tagName = dgnFileName;
                //string domain = tagName.Substring(1, tagName.LastIndexOf(@"/"));
                string fn = tagName.Remove(0, tagName.LastIndexOf(@"/") + 1);
                //download the file
                if (!System.IO.File.Exists(_pdfStoragePath + fn))
                {
                    try
                    {
                        cl.DownloadFile(tagName, _pdfStoragePath + fn);
                        Debug.WriteLine(" + file downloaded: " + fn);
                    }
                    catch
                    {
                        Debug.WriteLine(" Err. PIM Exception: fileName = " + fn);
                    }
                }
                else
                {
                    Debug.WriteLine(" ! file exists " + fn);
                }            
            }
            //catch
            //{ }

            //save into database
            db.SaveDrawing(db.CurrentID, dgnFileName);
            db.SaveDrawing(db.CurrentID, pdfFileName);

            //go to the next document
            IEnumerator enumerator = (db as IEnumerator);
            if (enumerator.MoveNext())
            {
                Debug.WriteLine(" ---------> new doc : " + (enumerator.Current as string));
                //System.Threading.Thread.Sleep(50);
                webBrowser.Navigate(String.Format("http://ti-sf.statoil.com/pimviewer36/PIMResultListDocument.aspx?ClassName=DocRevision&Name=*{0}*&Description=", enumerator.Current as string));
            }
            else
            {
                if (!bOnlyDownload)
                {
                    ConvertDPFtoTIFF();
                }
                
                dbManager.Disconnect();
            }
        }

        void ConvertDPFtoTIFF()
        {
            PIBV.AcrobatWrapper.ConvertPdfToTiff(MTViewer.Properties.Settings.Default.PdfStoragePath, MTViewer.Properties.Settings.Default.TiffStoragePath);    
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            ConvertDPFtoTIFF();
        }

        private void btnImportConvert_Click(object sender, EventArgs e)
        {
            bOnlyDownload = false;
            InitDownload();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            bOnlyDownload = true;
            InitDownload();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dbManager.Connect();

            db = dbManager.CreateObject<PID_Database>();
            
            PID_BlindingList bl = dbManager.CreateObject<PID_BlindingList>();
            
            bl.IndexBlindingTags(MTViewer.Properties.Settings.Default.PdfStoragePath, MTViewer.Properties.Settings.Default.Pdf2StoragePath);

            dbManager.Disconnect();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

    }
}
